package cn.edu.sdyu.ie.crs.api;

import cn.edu.sdyu.ie.crs.common.response.Result;
import cn.edu.sdyu.ie.crs.domain.User;
import io.swagger.annotations.ApiParam;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author: JT
 * @date: 2021/9/6
 * @Title: 登录管理
 */
@Tag(name = "登录管理", description = "登录相关接口")
@Slf4j
@RestController
@RequestMapping("api")
public class LoginController {

    @Resource
    private AuthenticationManager authenticationManager;

    @Operation(tags = "登录管理", summary = "用户登录")
    @PostMapping("/login")
    public Result<User> login(@ApiParam(value = "用户名") String username, @ApiParam(value = "密码") String password) {

        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authenticate = authenticationManager.authenticate(token);
        SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(authenticate);
        User user = (User)authenticate.getPrincipal();
        user.setPassword(null);
        return Result.success(user);
    }
}
